package com.zzjson.redis;

import com.zzjson.common.utils.PropertiesUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

/**
 * <p>****************************************************************************</p>
 * <li>Description : TODO </li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2021年03月02日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class JedisSentinelExample {
	public static Properties properties = PropertiesUtils.loadProperties("redis-sentinel");

	public static void main(String[] args) {

		JedisSentinelPool jedisSentinelPool = getSentinelPool();

		try (Jedis jedis = jedisSentinelPool.getResource()) {
			System.out.println(jedis.set("sentinel666", "zzjson"));
			System.out.println(jedis.get("sentinel666"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		//注意这里不是关闭连接，在JedisPool模式下，Jedis会被归还给资源池。
	}

	private static JedisSentinelPool getSentinelPool() {

		String masterName = "mymaster";

		JedisPoolConfig config = getPoolConfig();


		Set<String> sentinels = initSentinelHostAndPort();

		//JedisSentinelPool其实本质跟JedisPool类似，都是与redis主节点建立的连接池
		//JedisSentinelPool并不是说与sentinel建立的连接池，而是通过sentinel发现redis主节点并与其建立连接

		return new JedisSentinelPool(masterName, sentinels, config, 3000, null);
	}

	private static JedisPoolConfig getPoolConfig() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(20);
		config.setMaxIdle(10);
		config.setMinIdle(5);
		return config;
	}

	private static Set<String> initSentinelHostAndPort() {
		Set<String> sentinels = new HashSet<>();
		sentinels.add(new HostAndPort(properties.getProperty("host1"), Integer.parseInt(properties.getProperty("host1.port"))).toString());
		sentinels.add(new HostAndPort(properties.getProperty("host2"), Integer.parseInt(properties.getProperty("host2.port"))).toString());
		sentinels.add(new HostAndPort(properties.getProperty("host3"), Integer.parseInt(properties.getProperty("host3.port"))).toString());

		return sentinels;
	}
}